package com.gzc.just.play.last.war.sceneserver.goods;

import com.gzc.just.play.last.war.sceneserver.gameobject.unit.GameUnit;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 物品使用系统 - 处理物品的购买、使用、售卖等操作
 *
 * 对应C++的物品使用系统
 *
 * @author AI编程助手
 * @version 1.0
 * @since 2025-11-22
 */
public class GoodsUseSystem {
    
    private static final Logger log = LoggerFactory.getLogger(GoodsUseSystem.class);
    
    private final GameUnit owner;
    private final GoodsManager goodsManager;
    private final List<GoodsUseListener> listeners = new CopyOnWriteArrayList<>();
    
    /**
     * 创建物品使用系统
     *
     * @param owner 物品所有者
     * @param goodsManager 物品管理器
     */
    public GoodsUseSystem(GameUnit owner, GoodsManager goodsManager) {
        this.owner = owner;
        this.goodsManager = goodsManager;
    }
    
    /**
     * 购买物品
     *
     * @param goodsId 物品ID
     * @param quantity 购买数量
     * @return 是否购买成功
     */
    public boolean buyGoods(int goodsId, int quantity) {
        GoodsConfig config = goodsManager.getGoods(goodsId);
        if (config == null) {
            log.warn("物品不存在: {}", goodsId);
            return false;
        }
        
        // 计算总价
        int totalPrice = config.getPrice() * quantity;
        
        // 检查金币是否足够
        int currentGold = (int) owner.getAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.GOLD);
        if (currentGold < totalPrice) {
            log.debug("金币不足: 需要 {}, 拥有 {}", totalPrice, currentGold);
            notifyPurchaseFailed(goodsId, quantity, "金币不足");
            return false;
        }
        
        // 扣除金币
        owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.GOLD, -totalPrice);
        
        log.info("购买物品: ID={}, 数量={}, 总价={}", goodsId, quantity, totalPrice);
        notifyGoodsPurchased(goodsId, quantity, totalPrice);
        return true;
    }
    
    /**
     * 使用消耗品
     *
     * @param goodsId 物品ID
     * @param target 使用目标
     * @return 是否使用成功
     */
    public boolean useConsumable(int goodsId, GameUnit target) {
        GoodsConfig config = goodsManager.getGoods(goodsId);
        if (config == null) {
            log.warn("物品不存在: {}", goodsId);
            return false;
        }
        
        if (!config.isConsumable()) {
            log.debug("物品不是消耗品: {}", goodsId);
            return false;
        }
        
        if (target == null) {
            target = owner;
        }
        
        // 根据物品类型进行不同的处理
        GoodsType type = config.getGoodsType();
        boolean success = false;
        
        switch (type) {
            case HEALTH_POTION:
                // 恢复生命值
                target.restoreHealth(config.getHealthRestore());
                success = true;
                break;
                
            case MANA_POTION:
                // 恢复魔力值
                target.restoreMana(config.getManaRestore());
                success = true;
                break;
                
            case REVIVE_SCROLL:
                // 复活
                if (!target.isAlive()) {
                    target.revive(50);
                    success = true;
                }
                break;
                
            case TELEPORT_SCROLL:
                // 传送（这里仅记录，实际传送由其他系统处理）
                success = true;
                break;
                
            default:
                success = false;
        }
        
        if (success) {
            log.info("使用消耗品: ID={}", goodsId);
            notifyGoodsUsed(goodsId, target);
        }
        
        return success;
    }
    
    /**
     * 售卖物品
     *
     * @param goodsId 物品ID
     * @param quantity 售卖数量
     * @return 售卖所得金币
     */
    public int sellGoods(int goodsId, int quantity) {
        GoodsConfig config = goodsManager.getGoods(goodsId);
        if (config == null) {
            log.warn("物品不存在: {}", goodsId);
            return 0;
        }
        
        if (!config.isSellable()) {
            log.debug("物品不可售卖: {}", goodsId);
            return 0;
        }
        
        int salePrice = config.getSellPrice();
        int totalGold = salePrice * quantity;
        
        // 增加金币
        owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.GOLD, totalGold);
        
        log.info("售卖物品: ID={}, 数量={}, 获得={}", goodsId, quantity, totalGold);
        notifyGoodsSold(goodsId, quantity, totalGold);
        
        return totalGold;
    }
    
    /**
     * 装备物品
     *
     * @param goodsId 物品ID
     * @return 是否装备成功
     */
    public boolean equipGoods(int goodsId) {
        GoodsConfig config = goodsManager.getGoods(goodsId);
        if (config == null) {
            return false;
        }
        
        if (!config.isEquipment()) {
            log.debug("物品不是装备: {}", goodsId);
            return false;
        }
        
        // 应用属性加成
        if (config.getAttackBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.ATTACK, 
                config.getAttackBonus());
        }
        
        if (config.getDefenseBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.DEFENSE,
                config.getDefenseBonus());
        }
        
        if (config.getHealthBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.MAX_HEALTH,
                config.getHealthBonus());
        }
        
        if (config.getManaBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.MAX_MANA,
                config.getManaBonus());
        }
        
        log.info("装备物品: ID={}", goodsId);
        notifyGoodsEquipped(goodsId);
        return true;
    }
    
    /**
     * 卸下装备
     *
     * @param goodsId 物品ID
     * @return 是否卸下成功
     */
    public boolean unequipGoods(int goodsId) {
        GoodsConfig config = goodsManager.getGoods(goodsId);
        if (config == null) {
            return false;
        }
        
        if (!config.isEquipment()) {
            return false;
        }
        
        // 移除属性加成
        if (config.getAttackBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.ATTACK,
                -config.getAttackBonus());
        }
        
        if (config.getDefenseBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.DEFENSE,
                -config.getDefenseBonus());
        }
        
        if (config.getHealthBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.MAX_HEALTH,
                -config.getHealthBonus());
        }
        
        if (config.getManaBonus() > 0) {
            owner.modifyAttribute(com.gzc.just.play.last.war.sceneserver.attribute.AttributeType.MAX_MANA,
                -config.getManaBonus());
        }
        
        log.info("卸下装备: ID={}", goodsId);
        notifyGoodsUnequipped(goodsId);
        return true;
    }
    
    /**
     * 添加物品使用监听器
     */
    public void addListener(GoodsUseListener listener) {
        if (listener != null) {
            listeners.add(listener);
        }
    }
    
    /**
     * 移除物品使用监听器
     */
    public void removeListener(GoodsUseListener listener) {
        listeners.remove(listener);
    }
    
    /**
     * 物品事件通知
     */
    private void notifyGoodsPurchased(int goodsId, int quantity, int totalPrice) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onGoodsPurchased(goodsId, quantity, totalPrice);
            } catch (Exception e) {
                log.error("物品购买监听器异常", e);
            }
        }
    }
    
    private void notifyGoodsUsed(int goodsId, GameUnit target) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onGoodsUsed(goodsId, target);
            } catch (Exception e) {
                log.error("物品使用监听器异常", e);
            }
        }
    }
    
    private void notifyGoodsSold(int goodsId, int quantity, int totalGold) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onGoodsSold(goodsId, quantity, totalGold);
            } catch (Exception e) {
                log.error("物品售卖监听器异常", e);
            }
        }
    }
    
    private void notifyGoodsEquipped(int goodsId) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onGoodsEquipped(goodsId);
            } catch (Exception e) {
                log.error("物品装备监听器异常", e);
            }
        }
    }
    
    private void notifyGoodsUnequipped(int goodsId) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onGoodsUnequipped(goodsId);
            } catch (Exception e) {
                log.error("物品卸下监听器异常", e);
            }
        }
    }
    
    private void notifyPurchaseFailed(int goodsId, int quantity, String reason) {
        for (GoodsUseListener listener : listeners) {
            try {
                listener.onPurchaseFailed(goodsId, quantity, reason);
            } catch (Exception e) {
                log.error("购买失败监听器异常", e);
            }
        }
    }
}
